# ---------------------------------------------------------
# TUM - Technichal University of Munich
#
# Original Authors: Taylor Jones
#                   Magdalena Altmann
# Further Authors:  -
# Date: 2020-05-06
# Purpose: This source code intends to re-estimate CH4
#          emissions in Munich using a top-down approach.
#          This file provides functions that are used by
#          the main source file.
# Comment: This source code has been developed in 2019,
#          however the date above indicates the first
#          submit to version control.
# ---------------------------------------------------------

load_inv <- function(foot_file,flatten_prior=F,add_epa_ag=F){
  
###[Magda] we only have one sector
  # sectors <- c("total") ### Depreached. Defined in Run_Inversion.R
  prior_file  <- paste0(path_campaign,'/inventories/',inventory_file)
  coordslat_file_local <- paste0(path_campaign,'/inventories/',coordslat_file)
  coordslon_file_local <- paste0(path_campaign,'/inventories/',coordslon_file)
  ncin = nc_open(prior_file)
  latsnc = nc_open(coordslat_file_local)
  lonsnc = nc_open(coordslon_file_local)
  lats1 = as.vector(ncvar_get(latsnc,'la'))
  lons1 = as.vector(ncvar_get(lonsnc,'lo'))
  S <- SpatialPoints(cbind(lons1,lats1))

  conversion_factor <- 1.9756e-6 # mol/(km2*hr) -> umol/(m2*sec)
  
  ras_list <- NULL
  
###[Magda] s in 1:1 -> only one inventory: E_TRA1, otherwise: s in 1:n (E_TRAn)
  for( s in 1:1){
    ras <- raster(foot_file) #[taylor]
    if(s > 1){ #point sources
      ras <- rasterize(ps_df[s-1,],ras)$mag/2
    }else{
      
      prior_data = as.vector(ncvar_get(ncin,'CH4'))
      df <- data.frame("x1"=(prior_data*conversion_factor))
      sdf <- SpatialPointsDataFrame(S,df)
      ras <- rasterize(sdf,ras)
      ras <- resample(ras$x1,ras$x1,method="bilinear")
      if( flatten_prior){
        ras <- ras*0 + cellStats(ras,mean)
      }
    }
    ras[is.na(ras[])] <- 0
    if( (s==1)|(s==2)|(s==7)){
      ras_list <- c(ras_list, ras)
    }else if(s==6){
      ras_list[[1]] <- ras_list[[1]] + ras
    }else{
      ras_list[[length(ras_list)]] <- ras_list[[length(ras_list)]] + ras
    }
  }
  
  
  ras_stack <- stack( ras_list )
  names(ras_stack ) <- sectors
  output <- list( "sectors" = sectors, "ras_stack" = ras_stack)
  return(output)
}



load_inv2 <- function(inventory_file,foot_file="NONE",flatten_prior=F,add_epa_ag=F){
  prior_file  <- paste0(path_campaign,'/inventories/',inventory_file)
  ras_stack <- stack( prior_file )
  if( foot_file != "NONE"){
    ras <- raster(foot_file)
    ras_stack <- resample(ras_stack,ras,method="bilinear")
  }
  sectors <- names(ras_stack)
  output <- list( "sectors" = sectors, "ras_stack" = ras_stack)
  return(output)
}

